# 请求
import json
import random
import time
from hashlib import md5

import requests

url = 'http://fanyi.youdao.com/translate'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
    'Referer': 'http://fanyi.youdao.com/',
    'Cookie': 'OUTFOX_SEARCH_USER_ID=-1927650476@223.97.13.65;',

}

while True:
    kw = input('请输入需要翻译的语句（* 退出）:')
    if kw == "*":
        print("拜拜  宝~~~")
        break
    lts = str(int(time.time() * 1000))
    # print(lts)
    salt = lts + str(random.randint(0, 10))
    # print(salt)


    pre = 'fanyideskweb'
    last = 'Ygy_4c=r#e#4EX^NUGUc5'
    content = pre + kw + salt + last
    sign = md5(content.encode('utf-8')).hexdigest()
    # print(sign)

    data = {
        'i': kw,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': salt,
        'sign': '89d02509bdbdad0217172186a12f7dac',
        'lts': lts,
        'bv': 'ac3968199d18b7367b2479d1f4938ac2',
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_CLICKBUTTION',

    }

    response = requests.post(url, headers=headers, data=data)
    # 添加请求头  请求参数
    # 获取响应
    # print(response.status_code)
    data_str = response.content.decode('utf-8')

    data_dict = json.loads(data_str)
    result = data_dict.get('translateResult')[0][0].get('tgt')
    print('原文:' + kw + '\n翻译后:' + result)


